package jmeterBusiness;

import com.alibaba.fastjson.JSONObject;
import impl.TestServerBusinessImpl;
import models.GetRequestInputStream;
import models.HttpResponse;
import models.MyConfig;
import models.ReturnJson;
import tools.Http;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by yangxianming on 2019/9/19.
 * 将脚本分配到各个节点服务器
 */
public class ScriptDispense implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        ReturnJson returnJson = new ReturnJson();
        JSONObject jsonObject = GetRequestInputStream.getJson(request);
        String addresses = jsonObject.getString("address");
        String projectName = jsonObject.getString("projectName");
        String fileName = jsonObject.getString("fileName");

        //组装数据
        String splitMark = myConfig.getSplitMark("splitMark");
        String jmeterScriptDir = myConfig.getPropertiesConfig().getProperties().getProperty("appPath") + splitMark + "jmeterScript" + splitMark;
        //脚本位置
        String scriptLocation = jmeterScriptDir + projectName + splitMark;
        //组装请求参数
        JSONObject fileObject = new JSONObject();
        fileObject.put("fileName", fileName);
        fileObject.put("nameType", "file");
        JSONObject parJson = new JSONObject();
        parJson.put("fileObject", fileObject);
        JSONObject header = new JSONObject();
        header.put("Content-Type", "multipart/form-data;charset=UTF-8;");

        //循环分发
        String errMessage = "";
        for (String address: addresses.split(",")){
            String url = "http://" + address + "/uploadFile";
            Http http = new Http(scriptLocation);
            try {
                HttpResponse hr = http.sendRequest("post", header, url, parJson.toJSONString(), 10000);
                if (hr.getrCode() != 200){
                    returnJson.setApiStatus(0);
                    errMessage += address + "send script failed; ";
                }
            }catch (Exception e){
                returnJson.setApiStatus(0);
                errMessage += address + "send script failed; ";
            }
        }

        if (!Objects.equals(errMessage, "")){
            returnJson.setErrorMsg(errMessage);
        }
        return returnJson.toString();
    }

}
